<template>
  <view v-if="!isShowStayPopup" :class="classNameList">
    <x-draggable
      :disabled="!isFixed"
      :x="260"
      :y="120"
    >
      <view :style="[videoStyle]" class="_video">
        <video
          :muted="muted"
          :controls="false"
          :enable-progress-gesture="false"
          :src="fullscreenVideo.videoUrl"
          :autoplay="autoplay"
          :object-fit="objectFit"
          loop
          id="ref-full-video"
          @play="handlePlay"
          @click="handleClickVideo"
          @timeupdate="handleVideoTimeUpdate"
          @ended="handleVideoEnded"
        />
        <template v-if="isFixed">
          <view class="_close" @click.stop="handleCloseSmallVideo">
            <view class="_icon">
              <x-icon name="icon-025" size="24" color="#fff" />
            </view>
          </view>

          <view class="_sound" @click="handleChangeMuted">
            <view class="_icon">
              <x-icon :name="soundIcon" color="#fff" size="26" />
            </view>
          </view>
        </template>
        <x-image v-if="!isPlay" class="_pause" src="/assets/images/icon-play.png" @click="handleClickVideo" />
      </view>
    </x-draggable>
    <view class="_content">
      <view class="_mask" />
      <view class="_carousel">
        <view v-if="isShowCarousel" class="_marquee">
          <x-carousel :list="carouselList" :max="3" type="plain" />
        </view>
        <view v-if="pageType === 2" class="_sound" @click="handleChangeMuted">
          <x-icon :name="soundIcon" color="#fff" size="36" />
        </view>
      </view>
      <x-touch @change="handleTouchChange" @click="handleTouchChange">
        <view v-if="productTitle" class="_product">
          <view v-if="[2, 3].includes(pageType)" class="_product_block">
            <view v-if="productMainPic" class="_pic">
              <x-image mode="heightFix" :src="productMainPic" />
            </view>
            <view class="_info">
              <view class="_title">
                <text>{{ productTitle }}</text>
              </view>
              <view v-if="pageType === 3" class="_selling">{{ pageSellingPoint || '' }}</view>
              <view v-if="tagList && pageType === 2" class="_tags">
                <text v-for="item in tagList" :key="item">{{ item }}</text>
              </view>
              <view class="_tools">
                <view v-if="pageType === 2" class="_price">
                  <p-card-price
                    v-if="cardPrice"
                    :show-up-mark="productInfo.skuMode !== 1"
                    :has-coupon="!!couponAmount"
                    :value="cardPrice"
                  />
                </view>
                <view v-if="pageType === 3" class="_link">
                  <x-icon name="icon-068" size="26" color="#B6B6B6" />
                  <text>详情页面</text>
                </view>
                <view class="_button" @click.stop.prevent @touchend.stop.prevent>
                  <x-send-coupon v-if="couponSend" :coupon="couponSend" @sendcoupon="handleCustomEvent">
                    领券购买
                  </x-send-coupon>
                  <text v-else @touchend.stop="handleShowSku" @click.stop>
                    立即抢购
                  </text>
                </view>
              </view>
            </view>
          </view>
          <view v-if="pageType === 4" class="flex1">
            <view class="inline-block">
              <view class="_product_car">
                <view class="_pic">
                  <x-icon name="icon-060" size="36" color="#fff" />
                </view>
                <text>购物 | 视频同款</text>
              </view>
            </view>
            <view v-if="storeInfo" class="_store_name">
              @{{ storeInfo.storeName }}
            </view>
          </view>
          <view v-if="[3, 4].includes(pageType)" class="_sound" @click.stop="handleChangeMuted">
            <x-icon :name="soundIcon" color="#fff" size="36" />
          </view>
        </view>
        <view v-if="[3, 4].includes(pageType)" class="_video_title">
          <text>{{ fullscreenVideo.videoTitle }}</text>
        </view>
        <view class="_tips">
          <view class="_icon">
            <x-image src="/assets/images/icon-up-arrow.png"/>
          </view>
          <text>上滑或点击卡片查看详情</text>
        </view>
      </x-touch>

      <view class="_interaction">
        <!--店铺-->
        <view v-if="[3, 4].includes(pageType) && storeInfo" class="_store">
          <view class="_store_logo">
            <x-image :src="storeInfo.storeLogo" />
          </view>
          <view v-if="pageType === 3" class="_dt"> {{ storeInfo.storeName }} </view>
        </view>

        <!--观看-->
        <view v-if="isShowPv" class="_dl">
          <view class="_dd">
            <x-icon v-if="pageType === 3" name="icon-045" color="#fff" size="46" />
            <x-icon v-else name="icon-065" color="#fff" size="60" />
          </view>
          <view class="_dt">
            <text>{{ numberFormat(pv) }}</text>
          </view>
        </view>

        <!--分享-->
        <view class="_dl">
          <x-button openType="share" transparent styles="background: transparent;">
            <view class="_dd">
              <x-icon v-if="pageType === 3" name="icon-066" color="#fff" size="46" />
              <x-icon v-else name="icon-067" color="#fff" size="60" />
            </view>
            <view v-if="shareCount" class="_dt">
              <text>{{ numberFormat(shareCount) }}</text>
            </view>
          </x-button>
        </view>
      </view>
      <view class="safe-area-inset-bottom" />
    </view>
  </view>
</template>

<script>
import XSendCoupon from '@/components/x-send-coupon';
import XButton from '@/components/x-button';
import XTools from '@/utils/x-tools';
import XDraggable from '@/components/x-draggable';
import XTouch from '@/components/x-touch';
import XIcon from '@/components/x-icon';
import XImage from '@/components/x-image';
import XCarousel from '@/components/x-carousel';
import PCardPrice from '../card-price';

import { mapState } from 'vuex';

// 视频埋点信息
const videoInfo = {
  videoUrl: '',
  playFrequency: 0, // 视频循环播放次数
  playDuration: 0, // 当前视频播放时长
  playCurrentTime: 0 // 当前视频播放进度
};
export default {
  name: 'PVideo',
  components: {
    XSendCoupon,
    XButton,
    XDraggable,
    XTouch,
    XIcon,
    XImage,
    XCarousel,
    PCardPrice
  },
  props: {
    query: {
      type: Object,
      default: () => {}
    },
    storeInfo: {
      type: Object,
      default: () => null
    },
    autoplay: {
      type: Boolean,
      default: true
    },
    muted: {
      type: Boolean,
      default: false
    },
    // 查看数
    pv: {
      type: Number,
      default: 0
    },
    // 分享数
    shareCount: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      videoContext: null,
      isPlay: true,
      isFixed: false,
      // 当前商品关联的所有优惠券列表，已领取和可领取，支持单个领取的
      productCouponList: [],
      isAlreadyReceive: false // 是否已经领取过优惠券
    };
  },
  computed: {
    ...mapState({
      // 页面跳转状态，暂时使用pages的
      previousStatus: state => state['pages'].previousStatus,
      // 0关闭，1半打开，2全打开
      openProduct: state => state['product'].openProduct,
      // 商品信息
      productInfo: state => state['product'].productDetail,
      // 页面价格(最低sku价格)
      pagePrice: state => state['product'].pageDetail?.pagePrice,
      // 商品标题
      productTitle: state => state['product'].pageDetail?.pageProductTitle,
      // 商品卖点
      pageSellingPoint: state => state['product'].pageDetail?.pageSellingPoint,
      // 是否浏览人数配置
      isPageViewPv: state => state['product'].pageModule?.pageView,
      // 沉浸视频数据
      fullscreenVideo: state => state['product'].resourceModule?.fullscreenVideo || {},
      // 跑马灯数据
      carouselList: state => state['product'].carouselList,
      // 服务承诺
      safeguardList: state => state['product'].safeguardList,
      // 当前商品可使用的优惠券
      couponList: state => state['product'].couponList || [],
      // 当前商品关联的可领取优惠券，只支持批次领取，最多10个
      couponSend: state => state['product'].couponSend,
      // 返回出优惠金额弹框
      payCancelTwoVisible: state => state['pages'].payCancelTwoVisible,
      // 价格模块
      priceModule: state => state['product'].pageModule?.price
    }),
    // 页面类型
    pageType() {
      return Number(this.query.pageType);
    },
    classNameList() {
      const arr = ['p-video'];
      switch (this.pageType) {
        case 3:
          arr.push('is-medium');
          break;
        case 4:
          arr.push('is-small');
          break;
        default:
          arr.push('is-large');
      }
      if (this.isFixed) {
        arr.push('is-fixed');
      }
      return arr.join(' ');
    },
    // 商品主图
    productMainPic() {
      return this.productInfo?.productMainPic;
    },
    // 声音图标
    soundIcon() {
      return this.muted ? 'icon-056' : 'icon-057';
    },
    // 标签
    tagList() {
      if (this.safeguardList?.length) {
        const list = this.safeguardList.slice(0, 3);
        return list.map(item => item.dictNote);
      }
      return null;
    },
    // 是否显示领券按钮
    isShowCouponButton() {
      return this.couponSend;
    },
    // 是否显示跑马灯
    isShowCarousel() {
      return this.carouselList && this.openProduct === 0;
    },
    // 优惠券金额
    couponAmount() {
      const couponList = [...(this.couponList || [])];
      // 如果没有gdt_vid，再判断是否存在未领取的优惠券数据
      if (!this.query?.gdt_vid && this.couponSend?.couponVoList) {
      // 如果有，一并进行最优计算
        couponList.push(...this.couponSend.couponVoList.filter(coupon => coupon.usableStatus));
      }

      if (couponList && couponList.length) {
        const canUse = [];
        for (let j = 0; j < couponList.length; j++) {
          const coupon = couponList[j];
          const productPrice = XTools.formatNumber(this.pagePrice - this.promotionDiscountAmount);
          // couponType 类型：1-满减券；2-直减券，usableStatus
          if (coupon.couponType === 2 || productPrice >= coupon.transactionAmount) {
            canUse.push(couponList[j]);
          }
        }
        if (canUse.length > 0) {
          return canUse.sort((a, b) => {
            return b.couponAmount - a.couponAmount;
          })[0].couponAmount;
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    // 展示挽留弹窗
    isShowStayPopup() {
      return +this.query.previousStatus === 2 && this.payCancelTwoVisible;
    },
    isShowPv() {
      return this.pv >= 30 && [3, 4].includes(this.pageType) && this.isPageViewPv;
    },
    // 视频展示形式
    objectFit() {
      if (this.isFixed) {
        return 'cover';
      } else {
        if (this.isVertical) {
          return 'cover';
        } else {
          return 'contain';
        }
      }
    },
    // 视频尺寸
    videoStyle() {
      const style = {
        height: '1360rpx'
      };
      if (!this.isVertical) {
        // 横屏视频
        style.height = '85vh';
      } else if ([3, 4].includes(this.pageType)) {
        // 当视频原始高大于屏幕高
        style.height = '100vh';
      }
      return style;
    },
    // 是否竖屏
    isVertical() {
      const { width, height } = this.fullscreenVideo;
      if (width && height) {
        return height > width;
      } else {
        return true;
      }
    },
    // 大促金额
    promotionDiscountAmount() {
      return this.priceModule && this.priceModule.value === 2 ? this.priceModule.discountAmount : 0;
    },
    cardPrice() {
      const minSkuPrice = XTools.formatNumber(this.pagePrice);
      let finalPrice = minSkuPrice - this.promotionDiscountAmount;

      if (this.couponAmount) {
        finalPrice = finalPrice - this.couponAmount;
      }
      if (finalPrice <= 0) {
        finalPrice = 0.01;
      }

      return XTools.formatZero(finalPrice);
    }
  },
  watch: {
    // 监听显示状态
    openProduct() {
      this.setVideoContext();
    }
  },
  created() {},
  mounted() {
    this.videoContext = uni.createVideoContext('ref-full-video', this);
    Object.assign(videoInfo, {
      videoUrl: this.fullscreenVideo.videoUrl
    });
  },
  methods: {
    numberFormat: XTools.numberFormat,
    // 切换声音
    handleChangeMuted() {
      this.$emit('update:muted', !this.muted);
      this.$XTrack('immersiveVideoMutedClick', this.muted);
    },
    // 半展开
    handleTouchChange() {
      this.$emit('change', 'open');
    },
    // 查看sku
    handleShowSku() {
      this.$emit('buy', 'video');
    },
    handlePlay() {
      this.isPlay = true;
    },
    // 点击视频，切换播放状态
    handleClickVideo() {
      if (this.isFixed) {
        this.$store.dispatch('product/setData', {
          openProduct: 0
        });
        this.$XTrack('immersiveVideoSmallClick');
      } else {
        if (this.isPlay) {
          this.isPlay = false;
          this.videoContext.pause();
          this.$XTrack('immersiveVideoPauseClick');
        } else {
          this.videoContext.play();
          this.$XTrack('immersiveVideoPlayClick');
        }
      }
    },
    // 播放进度变化时触发
    handleVideoTimeUpdate({ detail }) {
      const { currentTime, duration } = detail;
      Object.assign(videoInfo, {
        playDuration: duration,
        playCurrentTime: currentTime
      });
      this.$XTrack('logsMapIndex', { videoLeveInfo: videoInfo });
    },
    // 当播放到末尾时触发
    handleVideoEnded() {
      Object.assign(videoInfo, {
        playFrequency: videoInfo.playFrequency + 1
      });
    },
    // 设置视频对象
    setVideoContext() {
      if (!this.videoContext) {
        this.videoContext = uni.createVideoContext('ref-full-video', this);
        Object.assign(videoInfo, {
          videoUrl: this.fullscreenVideo.videoUrl
        });
      }
      if (this.openProduct === 2) {
        if (this.fullscreenVideo?.pictureInPictureMode && this.previousStatus !== 2) {
          this.isFixed = true;
        } else {
          this.videoContext.pause();
        }
      } else {
        this.isFixed = false;
        if (this.isPlay) {
          this.videoContext.play();
        }
      }
    },
    // 领取优惠券后
    handleCustomEvent() {
      this.isAlreadyReceive = true;
      this.$emit('success', 'video');
    },
    // 关闭视频小窗口
    handleCloseSmallVideo() {
      this.isFixed = false;
      this.videoContext.pause();
    }
  }
};
</script>

<style lang="scss" scoped>
.p-video{
  height: 100vh; overflow: hidden; background-color: #000;
  ._video{
    width: 100%; max-height: 100vh; position: relative;
    video{ width: 100%; height: 100%; }
    ._pause{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 80px; height: 80px;}
  }
  ._sound{ width: 64px; height: 64px; border-radius: 50%; background-color: rgba(0, 0, 0, .3); display: flex; align-items: center; justify-content: center;}
  ._content{
    position: absolute; left: 0; bottom: 0; width: 100%; padding: 24px 24px 50px;
    ._mask{ position: absolute; bottom: 0; left: 0; width: 100%; height: 150px; background: linear-gradient(0deg, #000000 0%, rgba(0, 0, 0, 0) 100%);}
    ._carousel{
      display: flex; align-items: flex-end; padding-bottom: 24px; position: relative;
      ._marquee{ flex: 1;}
    }
    ._product{
      position: relative;
      ._product_block{ background-color: #fff; padding: 24px; border-radius: 12px; min-height: 100px; position: relative; display: flex;}
      ._pic{ height: 180px; border-radius: 6px; overflow: hidden;}
      ._info{ flex: 1; padding-left: 16px; display: flex; flex-direction: column;}
      ._title{
        font-size: 30px; color: $uni-color-default;
        text{ text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;}
      }
      ._selling{ font-size: 24px; width: 80%; height: 40px; padding-top: 4px; color: #D4D4D4; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden;}
      ._tags{
        display: flex; align-items: center; padding-top: 10px;
        text{ margin-right: 12px; flex-shrink: 0; padding: 0 8px; border-radius: 4px; border: 1px solid $uni-color-warning; box-sizing: border-box; font-size: 22px; color: $uni-color-primary;}
      }
      ._tools{
        display: flex; align-items: center; padding-top: 15px;
        ._price{ flex: 1;}
        ._link{
          flex: 1; display: flex; align-items: center; color: #B6B6B6; font-size: 24px; line-height: 1;
          text{ padding-left: 5px;}
        }
        ._button{ font-size: 30px; color: #fff; text-align: center; padding: 18px 22px; height: 68px; display: flex; align-items: center; justify-content: center; background: linear-gradient(90deg, #FF3728 0%, #FF8F27 100%); border-radius: 72px;}
      }
    }
    ._video_title{
      position: relative; padding-top: 10px; padding-bottom: 20px;
      text{ overflow: hidden; display: block;color: #fff;  text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;}
    }
    ._tips{
      text-align: center; display: flex; align-items: center; justify-content: center; color: #fff; position: relative; padding: 24px 0; animation: upAndDown .4s infinite alternate;
      ._icon{ width: 32px; height: 32px;}
      text{ font-size: 28px; opacity: .9; padding: 0 10px;}
    }
    ._interaction{
      position: relative;
      ._dt{ font-size: 26px; line-height: 1; overflow: hidden; color: #fff; text-align: center; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; }
      ._dd{ display: flex; align-items: center; justify-content: center;}
      ._store_logo{ width: 86px; height: 86px; border-radius: 50%; overflow: hidden; margin: 0 auto;}
    }
  }

  // 悬浮视频小窗
  &.is-fixed{
    ._video{
      width: 200px; height: 300px !important; position: relative;
      ._sound,
      ._close{
        position: absolute; right: 4px; top: 4px;
        ._icon{ border-radius: 50%; width: 48px; height: 48px; background: rgba(0, 0, 0, 0.3); display: flex; align-items: center; justify-content: center;}
      }
      ._sound{ bottom: 4px; top: auto; width: 48px; height: 48px;}
    }
  }

  // 大卡
  &.is-large{
    ._interaction{
      position: absolute; right: 16px; bottom: 550px; display: flex; flex-direction: column;
      ._dl{ padding: 10px;}
    }
  }
  // 中卡
  &.is-medium{
    ._tips{ display: none;}
    ._mask{ height: 300px;}
    ._video_title{
      text{ font-size: 28px;}
    }
    ._product{
      display: flex;
      ._product_block{ flex: 1; background: rgba(0, 0, 0, 0.3); border-radius: 6px; padding: 13px; margin-right: 16px;}
      ._pic{ height: 140px;}
      ._title{
        color: #fff;
        text{ -webkit-line-clamp: 1;}
      }
      ._tools{
        ._button{ font-size: 30px; padding: 0 10px; height: 52px; line-height: 52px; background: linear-gradient(0deg, #15C434, #15C434), #15C434; border-radius: 10px;}
      }
    }
    ._interaction{
      display: flex; align-items: flex-end; min-width: 450px; padding: 20px 0 0;
      ._store{
        display: flex; align-items: center; flex: 1;
        ._dt{ flex: 1; font-size: 28px; text-align: left; color: #fff;}
      }
      ._dl{ padding: 0 20px;}
      ._store_logo{ margin-right: 16px;}
    }
  }
  // 小卡
  &.is-small{
    ._tips{ display: none;}
    ._mask{ height: 300px;}
    ._video_title{
      height: 110px;
      text{ font-size: 24px;}
    }
    ._product{
      display: flex; align-items: flex-end;
      .inline-block{ display: inline-block;}
      ._product_car{
        display: flex; align-items: center; background: rgba(0, 0, 0, 0.3); border-radius: 12px; padding: 10px; color: #fff; font-size: 28px;
        ._pic{ width: 46px; height: 46px; display: flex; justify-content: center; align-items: center; background-color: #FE813A; border-radius: 6px; margin-right: 16px;}
      }
      ._store_name{ font-size: 32px; padding: 50px 0 14px; color: #fff;}
    }
    ._interaction{
      position: absolute; right: 16px; bottom: 550px; display: flex; flex-direction: column;
      ._store{ padding-bottom: 30px;}
      ._dl{ padding: 10px;}
      ._dd{ opacity: .9;}
      ._store_logo{ border: 3px solid #fff;}
    }
  }
}

@keyframes upAndDown {
  from{
    transform: translate(0, 20px);
    transform-origin: center center;
  }
  to{
    transform: translate(0, 0);
    transform-origin: center center;
  }
}
</style>
